import React, { useState, useEffect, useRef } from 'react';
import { connect } from 'react-redux';
import { Tabs, Button, Row, Col, Form, message } from 'antd';
import Base from '../Strategy/form/templateBase';
import Flow from '../Strategy/flow/flow';
import services from '../../../services/api';
import useVariableData from '../../../hook/useVariableData';
import { USAGE_SCOPE_LIMIT, VARIABLE_TYPE } from '../../../utils/constant';
import { randomKey } from '../../../utils/utils';
import useActionsData from 'src/hook/useActionsData';
import { NODE } from 'src/components/Flow/utils/constants';
import { getComponent } from 'src/components/Flow/utils/component';
import ReturnVariables from '../Strategy/flow/returnVariables';
import './index.less';

//activeKey
const _TAB_KEYS = {
  _CONFIG: '_CONFIG',
  _RETURN: 'return',
};

/**
 * @method StrategyAdd
 */

function StrategyAdd(props) {
  const [activeKey, setActiveKey] = useState(_TAB_KEYS._CONFIG);
  const [appId, setAppId] = useState('');
  const [eventId, setEventId] = useState('');
  const [detail, setDetail] = useState({});
  const [importData, setImportData] = useState([]);
  const [operator, setOperator] = useState([]);
  const [returnResults, setReturnResults] = useState([]); // 返回变量全部的列表
  const [returnVariable, setReturnVariable] = useState([]); // 选中的返回变量

  const [flows, setFlows] = useState({
    nodes: [
      {
        ...getComponent(NODE._START),
        x: 300,
        y: 100,
        id: randomKey(),
      },
    ],
    edges: [],
  });
  const variable = useVariableData({
    limitType: [
      VARIABLE_TYPE._FIELD,
      VARIABLE_TYPE._FEATURE,
      VARIABLE_TYPE._MODEL,
      VARIABLE_TYPE._NAMELIST,
      VARIABLE_TYPE._THIRD_FEATURE,
      VARIABLE_TYPE._STRATEGY,
      VARIABLE_TYPE._RISK_LEVEL,
      VARIABLE_TYPE._LITERAL,
    ],
    appId,
    eventId,
    codes: props.codes,
   }
  );
  const actions = useActionsData(USAGE_SCOPE_LIMIT._STRATEGY); //获取动作函数的列表

  const _flow = useRef(); //flow对象
  const _returns = useRef(); //返回变量对象

  useEffect(() => {
    if (props.actionType !== 'detail') {
      props.dispatch({ type: 'pageClose/waringAdd' });
    }
    return () => {
      if (props.actionType !== 'detail') {
        props.dispatch({ type: 'pageClose/waringReduce' });
      }
    }
  }, [])

  useEffect(() => {
    getOperator(); // 获取操作符
    if (props.id) {
      getDetail(props.id);
    }
    if (props.value && Object.keys(props.value).length > 0) {
      setDetailData(props.value);
    }
  }, []);
  useEffect(() => {
    if (props.value && Object.keys(props.value).length > 0) {
      setDetailData(props.value);
    }
  },[props.value])

  // 获取详情
  function getDetail(id) {
    const params = { strategy_template_id: id };
    services.template.queryOne(params).then((res) => {
      if (res.code === 0) {
        setDetailData(res.data);
      } else {
        message.error(res.msg);
      }
    });
  }

  // 设置detail数据
  function setDetailData(data) {
    setDetail(data);
    const newContent = (Object.keys(data.content).length && data.content) || data;
    const lists = newContent.components || [];
    setImportData(lists);
    setAppId(newContent.app_id);
    setEventId(newContent.event_id);
    if (!newContent.strategy_config) return;
    newContent.strategy_config.mode.flows.nodes = newContent.strategy_config.mode.flows.nodes.map((it) => {
      // 这里重组strategy的节点的 is_break
      if (it.strategy_id && newContent.is_break_group && newContent.is_break_group.includes(it.strategy_id)) {
        it.is_break = true;
      } else {
        delete it.is_break;
      }
      return it;
    });
    setFlows(newContent.strategy_config.mode.flows);
    setReturnVariable(newContent.strategy_config.mode.return_variables);
    setReturnResults(newContent.returns);
  }

  // 获取操作符
  function getOperator() {
    services.policy.operator({}).then((res) => {
      if (res.code === 0) {
        setOperator(res.data);
      }
    });
  }
  // function getFlowData() {
  //   const data = _flow.current.save();
  //   const start = data.nodes.find((item) => item.type === NODE._START);

  //   if (!start) {
  //     throw '请添加开始节点';
  //   }
  //   const startSource = data.edges.find((item) => item.source === start.id);
  //   if (!startSource) {
  //     throw '请为开始节点连线';
  //   }

  //   // 查找出挑战组节点的名称数组
  //   const _challengesNames = data.nodes.filter((item) => item.type === NODE._CHALLENGE).map((it) => it.name);
  //   //如果他们的长度不一样，则说明有重复的组名
  //   if (isRepeatArr(_challengesNames)) {
  //     throw '冠军挑战节点的名称重复!';
  //   }
  //   data.nodes.forEach((item) => {
  //     const edge = data.edges.find((it) => {
  //       return it.source === item.id || it.target === item.id;
  //     });
  //     if (!edge) {
  //       throw '请为未连线的节点连线';
  //     }
  //     if (item.type === NODE._CHALLENGE) {
  //       validateChallenge(item, (err) => message.warning(err));
  //     }

  //     // 节点，需要验证他下面是否有多条线，如果大于等于2条，则必须配置edges_configs
  //     const edges = data.edges.filter((it) => it.source === item.id);
  //     const { edge_configs = [] } = item;
  //     const configs = edge_configs.filter((it) => edges.some((edge) => edge.id === it.id));

  //     // 如果线大于两条，则需要验证必须配置分流条件
  //     if (edges.length >= 2) {
  //       // 如果configs的长度不等于edges的长度，则遍历edges，把没有配置的线高亮
  //       if (configs.length !== edges.length) {
  //         edges.forEach((it) => {
  //           if (!configs.some((config) => config.id === it.id)) {
  //             highLightEdge(it.id);
  //           }
  //         });
  //         throw `请配置${item.name}下的分流条件`;
  //       } else {
  //         // 如果如果edge_configs的长度大于edges的长度,则把过滤后的数据赋值给item.edge_config
  //         if (edge_configs.length > edges.length) {
  //           item.edge_configs = configs;
  //         }
  //       }

  //       // 如果只有一条线
  //     } else if (edges.length === 1) {
  //       const { id, source, target } = edges[0];
  //       // 如果configs为空，则需要默认给他添加上id,source,target，引擎需要。。。
  //       if (configs.length === 0) {
  //         item.edge_configs = [{ id: id, source: source, target: target }];
  //       } else {
  //         item.edge_configs = configs;
  //       }
  //     }
  //   });
  //   return data;
  // }

  // 高亮线
  // function highLightEdge(id) {
  //   const edge = _flow.current.findById(id);
  //   _flow.current.setItemState(edge, 'warning', true);
  // }

  // function getValues() {
  //   return new Promise((resolve, reject) => {
  //     props.form.validateFields((err, values) => {
  //       if (!err) {
  //         const flows = getFlowFinallyConfig();
  //         if (!flows) {
  //           reject();
  //         }
  //         const params = {};
  //         params.app_id = values.app_id;
  //         params.event_id = values.event_id;
  //         params.name = values.name;
  //         params.remark = values.remark;
  //         params.strategy_config = {
  //           mode: {
  //             flows,
  //           },
  //         };
  //         resolve(params);
  //       } else {
  //         reject();
  //       }
  //     });
  //   });
  // }
  function changeForm(data) {
    let obj = props.form.getFieldsValue();
    if (data) {
      obj.dept_ids = data;
    }
    props.changeForm && props.changeForm(obj);
  };
  // 提交
  function handleSubmit(e) {
    e.preventDefault();
    props.form.validateFields((err, values)=>{
      if(!err) {
        let params = {
          name: values.name,
          remark: values.remark,
          dept_ids: values.dept_ids.map(item => item.value),
          strategy_template_id: detail.strategy_template_id
        }
        services.template.edit(params).then((res) => {
          if (!res.code) {
            message.success(res.msg);
            props.history.push('/strategy/Template');
          } else {
            message.error(res.msg);
          }
        });
      }
    })
  }

  /**  获取流程策略最终的配置信息
   */
  // function getFlowFinallyConfig() {
  //   const finallyConfig = {};
  //   try {
  //     const data = getFlowData();
  //     finallyConfig.nodes = data.nodes;
  //     finallyConfig.edges = data.edges;
  //     return finallyConfig;
  //   } catch (err) {
  //     message.warning(err);
  //     return false;
  //   } finally {
  //     console.log('heh');
  //   }
  // }

  function handleRef(ref) {
    _flow.current = ref;
    props.onRef && props.onRef(_flow.current);
  }

  function handleChangeTab(key) {
    // 如果是返回变量
    if (key === _TAB_KEYS._RETURN) {
        setActiveKey(key);
        return
      // getValues()
      //   .then((params) => {
      //     services.strategyFlow.returns(params).then((res) => {
      //       if (res.code === 0) {
      //         console.log('sssssss', res.data)
      //         setReturnResults(res.data);
      //         setActiveKey(key);
      //       } else {
      //         message.error(res.msg);
      //       }
      //     });
      //   })
      //   .catch((err) => {});
    } else {
      setActiveKey(key);
    }
  }

  function renderBaseSetting() {
    return (
      <>
        <div className='tantuer-field-area'>
          <div className='form-title'>基本信息</div>

          <Base
            {...props}
            value={detail}
            changeForm={changeForm}
            actionType={props.actionType}
            localSubmit={props.localSubmit}
          />
        </div>
        {eventId && (
          <div className='tantuer-field-area'>
            <div className='form-title'>配置策略</div>
            <Tabs style={{ width: '100%' }} activeKey={activeKey} onChange={(activeKey) => handleChangeTab(activeKey)}>
              <Tabs.TabPane tab={'策略配置'} key={_TAB_KEYS._CONFIG} forceRender={true}>
                <Flow
                  {...props}
                  appId={appId}
                  eventId={eventId}
                  variable={variable}
                  operator={operator}
                  key={eventId}
                  value={flows}
                  actions={actions}
                  wp={props.wp}
                  importData={importData}
                  onRef={(ref) => handleRef(ref)}
                  disabled={true}
                  graphicMode={'disabled'}
                  strategy_flow_mode={props.codes && props.codes.strategy_flow_mode}
                  localSubmit={props.localSubmit}
                  strategy_mode={(props.codes && props.codes.strategy_mode) || []}
                  compareData={
                    (props.compareData &&
                      props.compareData.strategy_config &&
                      props.compareData.strategy_config.mode &&
                      props.compareData.strategy_config.mode.flows) ||
                    {}
                  }
                />
              </Tabs.TabPane>

              <Tabs.TabPane tab={'返回变量'} key={_TAB_KEYS._RETURN} forceRender={true}>
                <ReturnVariables
                  {...props}
                  returnResults={returnResults || []}
                  codes={(props.codes && props.codes.return_variable) || []}
                  value={returnVariable}
                  createRef={_returns}
                  disabled={true}
                  compareData={
                    (props.compareData &&
                      props.compareData.strategy_config &&
                      props.compareData.strategy_config.mode &&
                      props.compareData.strategy_config.mode.return_variables) ||
                    []
                  }
                />
              </Tabs.TabPane>
            </Tabs>
          </div>
        )}
      </>
    );
  }

  return (
    <div className='stretegy-content'>
      <div className='stretegy-wp tantuer-form ' id='intro-farm' style={{ position: 'relative' }}>
        <Form onSubmit={() => false} className='stretegy-wp-form'>
          {renderBaseSetting()}

          <Row type='flex' justify='start' className='form-submit-area'>
            <Col>
              {props.actionType !== 'detail' && (
                 <>
                   <Button
                     type='primary'
                     onClick={handleSubmit}
                     data-intro='点击确认，流程编辑完毕，系统按照您设计的流程执行'
                     data-step='3'
                   >
                     确定
                   </Button>
                   <Button style={{ marginLeft: '15px' }} onClick={() => props.closeModal()}>
                     取消
                   </Button>
                 </>
              )}
            </Col>
          </Row>
        </Form>
      </div>
    </div>
  );
}
function mapStateToProps(state) {
  return {
    codes: {
      ...state.code,
    },
  };
}
export default connect(mapStateToProps)(Form.create()(StrategyAdd));
